package com.du.ichat;

import android.Manifest;
import android.annotation.TargetApi;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import com.du.ichat.utils.BaseActivity;
import com.netease.nimlib.sdk.media.player.AudioPlayer;
import com.netease.nimlib.sdk.media.player.OnPlayListener;
import com.netease.nimlib.sdk.media.record.AudioRecorder;
import com.netease.nimlib.sdk.media.record.IAudioRecordCallback;
import com.netease.nimlib.sdk.media.record.RecordType;

import java.io.File;

public class TestActivity extends BaseActivity {
    private IAudioRecordCallback callback = null;
    private AudioRecorder a;
    private AudioPlayer player;
    private File f;
    private MediaRecorder recorder;
    private int BASE = 600;
    private int SPACE = 200;
    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA,Manifest.permission.READ_PHONE_STATE , Manifest.permission.RECORD_AUDIO} , 101);

        f = new File(Environment.getExternalStorageDirectory() , "a.3gp");

        callback = new IAudioRecordCallback() {
            @Override
            public void onRecordReady() {
                log("onRecordReady");
            }

            @Override
            public void onRecordStart(File file, RecordType recordType) {
                log("onRecordReady :" + file.getAbsolutePath());
                log("onRecordReady recordType:" + recordType.getFileSuffix());
                f = file;

                updateMicStatus();
            }

            @Override
            public void onRecordSuccess(File file, long l, RecordType recordType) {
                log("onRecordSuccess");
                log("onRecordSuccess file : " + file.getAbsolutePath());
                log("onRecordSuccess l: " + l);
                log("onRecordSuccess recordType : " + recordType.getFileSuffix());
                f = file;
            }

            @Override
            public void onRecordFail() {
                log("onRecordFail");
            }

            @Override
            public void onRecordCancel() {
                log("onRecordCancel");
            }

            @Override
            public void onRecordReachedMaxTime(int i) {
                log("onRecordReachedMaxTime : " + i);
            }
        };

        a = new AudioRecorder(this , RecordType.AMR , 60 , callback);

        // 定义一个播放进程回调类
        OnPlayListener listener = new OnPlayListener() {

            // 音频转码解码完成，会马上开始播放了
            public void onPrepared() {}

            // 播放结束
            public void onCompletion() {}

            // 播放被中断了
            public void onInterrupt() {}

            // 播放过程中出错。参数为出错原因描述
            public void onError(String error){}

            // 播放进度报告，每隔 500ms 会回调一次，告诉当前进度。 参数为当前进度，单位为毫秒，可用于更新 UI
            public void onPlaying(long curPosition) {}
        };

// 构造播放器对象
       player = new AudioPlayer(this, null, listener);


        if(recorder!=null){
            recorder.stop();
            recorder.release();
            recorder=null;
        }
        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);//声音来源是话筒
        recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);//设置格式
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//设置解码方式
        recorder.setOutputFile(f.getAbsolutePath());
        try {
            recorder.prepare();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        recorder.start();




    }

    public void click(View view) {
//        a.startRecord();

        new Thread(){
            @Override
            public void run() {
                while(true){

                    updateMicStatus();
                    try {
                        sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();


    }

    public void click2(View view) {
        a.completeRecord(true);
    }

    public void bofang(View view) {
        player.setDataSource(f.getAbsolutePath());
        player.start(AudioManager.STREAM_MUSIC);
    }

    private void updateMicStatus() {
        if(recorder!=null){
            int ratio = recorder.getMaxAmplitude() / BASE;
            int db = 0;// 分贝
            if (ratio > 1)
                db = (int) (20 * Math.log10(ratio));
//            System.out.println("分贝值："+db+"     "+Math.log10(ratio));
            log("分贝值："+db+"     "+Math.log10(ratio));
            //我对着手机说话声音最大的时候，db达到了35左右，
//            mHandler.postDelayed(mUpdateMicStatusTimer, SPACE);
//            //所以除了2，为的就是对应14张图片
//            mHandler.sendEmptyMessage(db/2);
        }
    }


}
